package com.lifang.imgsoa.util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

import com.aliyun.openservices.ClientException;
import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.OSSException;
import com.aliyun.openservices.oss.model.ObjectMetadata;

/**
 * @author Administrator
 * 水印    阿里云OSS工具类
 */
public class OSSObjectUtilWater extends OSSObjectUtilBase {

	private static String accessKeyID = Global.ACCESSKEYID_WATER;
	private static String accessKeySecret = Global.ACCESSKEYSECRET_WATER;
	private static String bucketName = Global.BUCKETNAME_WATER;
	private final static long cacheTime = 360 * 24 * 60 * 60 * 1000L;
	
	private static OSSObjectUtilWater ossObjectUtilWater = new OSSObjectUtilWater(accessKeyID, accessKeySecret, bucketName);

	private OSSObjectUtilWater(String accessKeyID, String accessKeySecret, String bucketName) {
		super(accessKeyID, accessKeySecret, bucketName);
	}

	public static OSSObjectUtilWater getInstance() {
		return ossObjectUtilWater;
	}
	
	public void uploadFile(OSSClient client, String bucketName, String key, String filename) throws OSSException, ClientException, IOException {
        File file = new File(filename);

        ObjectMetadata objectMeta = new ObjectMetadata();
        long now = new Date().getTime();
		objectMeta.setContentLength(file.length());
		objectMeta.setCacheControl("max-age=" + (cacheTime / 1000));
		objectMeta.setLastModified(new Date(now));
		objectMeta.setExpirationTime(new Date(now + cacheTime));
		
        // 可以在metadata中标记文件类型
        objectMeta.setContentType("image/jpeg");

        InputStream input = new FileInputStream(file);
        client.putObject(bucketName, key, input, objectMeta);
        input.close();
	}
	
	public void uploadFile_stream(OSSClient client, String bucketName, String key, byte[] filebytes) throws OSSException, ClientException, IOException {

        ObjectMetadata objectMeta = new ObjectMetadata();
        long now = new Date().getTime();
		objectMeta.setContentLength(filebytes.length);
		objectMeta.setCacheControl("max-age=" + (cacheTime / 1000));
		objectMeta.setLastModified(new Date(now));
		objectMeta.setExpirationTime(new Date(now + cacheTime));
		
        // 可以在metadata中标记文件类型
        objectMeta.setContentType("image/jpeg");

        InputStream input = new ByteArrayInputStream(filebytes);
        client.putObject(bucketName, key, input, objectMeta);
        input.close();
	}
}
